<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\service\SuperSubsidy\YouZanGoods;
use Biz\service\SuperSubsidy\YouZanGoodsInfo;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Biz\model\SuperSubsidy\YouZanBrandGoodsModel;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class SubsidyBrandGoodsController extends Controller
{
    const PAGE_SIZE = 20;

    public function goodsList(Request $request, Content $content)
    {
        Admin::script($this->operateGoodsScript());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $spuCode = trim($request->input('spu_code', ''));
        $spuNo = trim($request->input('spu_no', ''));
        $itemId = trim($request->input('item_id', ''));
        $name = trim($request->input('name', ''));
        $brandUserId = trim($request->input('brand_user_id', 0));
        if ($spuCode) {
            $where['spu_code'] = $spuCode;
        }
        if ($spuNo) {
            $where['spu_no'] = $spuNo;
        }
        if ($itemId) {
            $where['item_id'] = $itemId;
        }
        if ($name) {
            $where['name[~]'] = $name;
        }
        if ($brandUserId) {
            $where['brand_user_id'] = $brandUserId;
        }
        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['status' => 'ASC', 'id' => 'DESC'];
        list($list, $count) = YouZanGoods::getBrandGoodsList($where);
        // 处理查询条件
        $brandOption = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $brandOption = array_column($brandOption, 'brand_name', 'id');
        unset($where['LIMIT']);
        $total = YouZanBrandItemModel::count($where);
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $brandOption) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) use ($brandOption) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($brandOption) {
                    $filter->equal('brand_user_id', '品牌账户')->select($brandOption);
                    $filter->equal('name', '商品名称');
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('spu_code', '商品编码(BM**)');
                    $filter->equal('spu_no', '商品条码(P**)');
                    $filter->equal('item_id', '商品ID');
                });
            });
            $grid->disableExport();
            $grid->disableBatchActions();
            $grid->column('id', 'id');
            $grid->column('brand_name', '品牌名称');
            $grid->column('name', '商品名称')->display(function () {
                $html = '<ul class="list-unstyled">';
                $html .= '<li><a href="' . url('/admin/SuperSubsidy/brand/goodsList/' . $this->id . '/detail') . '">' . $this->name . '</a></li>';
                $html .= '<li>条码:' . $this->spu_no . '</li>';
                if ($this->item_id) {
                    $html .= '<li>ID:' . $this->item_id . '</li>';
                }
                $html .= '</ul>';
                return $html;
            });
            $grid->column('spu_code', '商品编码')->copyable();
            $grid->column('photo_url', '商品图片')->display(function () {
                foreach ($this->photo_url as $img) {
                    $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $img . '\'});">';
                    $html .= "<img src='" . $img . "' style='max-width:50px;max-height:50px' class='img img-thumbnail' />";
                    $html .= '</a>';
                }
                return $html;
            });
            $grid->column('supply_price', '供货价');
            $grid->column('market_price', '市场价');
            $grid->column('min_price', '最低限价');
            $grid->column('goods_service', '售后服务')->display(function () {
                $arr = explode(',', $this->goods_service);
                if ($arr) {
                    $html = '<ul class="list-unstyled">';
                    foreach ($arr as $row) {
                        $html .= '<li>' . YouZanBrandGoodsModel::GOODS_SERVICE_MAP[$row] . '</li>';
                    }
                    $html .= '</ul>';
                    return $html;
                }
            });
            $grid->column('skus', '规格信息')->display(function () {
                if ($this->sku_info) {
                    $html = '<ul class="list-unstyled">';
                    foreach ($this->sku_specs as $spec) {
                        $html .= '<li>' . $spec['key']['k'] . '：';
                        $values = array_column($spec['values'], 'v');
                        $html .= implode('，', $values);
                        $html .= '</li>';
                    }
                    $html .= '</ul>';
                    return $html;
                }
            });
            $grid->column('status', '状态')->display(function () {
                $html = '<ul class="list-unstyled">';
                if (YouZanBrandGoodsModel::STATUS_WAIT_UPDATED == $this->status) {
                    $html .= '<li>已编辑 ' . $this->status_desc . '</li>';
                    $html .= '<li><a class="fa fa-refresh refresh-goods" data-id="' . $this->id . '" href="javascript:void(0);">已更新</a></li>';
                } else if (YouZanBrandGoodsModel::STATUS_WAIT_RELEASE == $this->status) {
                    $html .= '<li>' . $this->status_desc . '</li>';
                    $html .= '<li><a class="fa fa-send release-goods" data-id="' . $this->id . '" href="javascript:void(0);">发布</a></li>';
                } else if (YouZanBrandGoodsModel::STATUS_RELEASE == $this->status) {
                    $html .= '<li>' . $this->status_desc . '</li>';
                    $html .= '<li><a class="fa fa-download" target="_blank" href="' . url('/admin/SuperSubsidy/brand/goodsList/' . $this->id . '/exportItem') . '">下载item商品</a></li>';
                }
                $html .= '<li>' . $this->update_at . '</li>';
                $html .= '</ul>';
                return $html;
            });
            $grid->disableActions();
            $grid->header(function () {
                $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;「已编辑 待更新」状态为品牌重新编辑了商品信息，需要手动同步到有赞网店商品。操作完之后，点击「已更新」更新为「已发布」状态。</span>';
                $html .= '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;「已发布」状态的商品，可以下载有赞网店商品的基础信息，运营可以参照自行同步到「品牌商品列表」。如果品牌提交的SKU信息和网店商品SKU对不上，则会下载失败。</span>';
                $html .= '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;「待发布」状态的商品为品牌创建商品信息后发生了延迟，未成功发布到商品库，可以点击「发布」按钮去发布到网店。</span>';
                return $html;
            });
        });
        $tab = new Tab();
        $tab->addLink('品牌商品列表', url('/admin/SuperSubsidy/brand/itemList'));
        $tab->add('品牌提交到商品库', $grid->render(), true);
        $content->row($tab);
        return $content
            ->header("超级补贴 | 品牌商品库列表")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 品牌商品库列表', 'url' => url('/admin/SuperSubsidy/brand/goodsList')], ['text' => '商品库列表']);
    }

    public function goodsDetail(Request $request, Content $content, $id)
    {
        $info = YouZanGoods::getBrandGoodsInfo($id);
        if ($info) {
            $tab = new Tab();
            $baseForm = new Form($info);
            $baseForm->hidden('id', 'id');
            $baseForm->text('brand_name', '品牌')->setWidth(4, 2)->readonly();
            $baseForm->text('name', '商品名称')->required()->setWidth(4, 2)->readonly();
            $baseForm->text('spu_code', '商品编码')->required()->setWidth(4, 2)->readonly();
            $baseForm->text('spu_no', '商品条码')->required()->setWidth(4, 2)->readonly();
            $baseForm->text('item_id', '有赞商品ID')->required()->setWidth(4, 2)->readonly();
            $baseForm->text('category', '商品分类')->required()->setWidth(4, 2)->readonly();
            $baseForm->multipleImage('white_img', '商品透明底图')->options(['showBrowse' => false, 'showCaption' => false, 'showPreview' => true])->readonly();;
            $baseForm->multipleImage('photo_url', '商品图片')->options(['showBrowse' => false, 'showCaption' => false,'showPreview' => true])->readonly();
            $baseForm->text('sell_point', '商品卖点')->setWidth(4, 2)->readonly();
            $baseForm->text('goods_service', '商品售后服')->setWidth(4, 2)->readonly();
            $baseForm->text('status_desc', '状态')->setWidth(4, 2)->readonly();
            if (!$info['sku_info']) {
                $baseForm->decimal('supply_price', '供货价')->readonly()->setWidth(4, 2);
                $baseForm->decimal('market_price', '市场价')->readonly()->setWidth(4, 2);
                $baseForm->decimal('min_price', '最低限价')->readonly()->setWidth(4, 2);
                $baseForm->decimal('total_stock', '总库存')->readonly()->setWidth(4, 2);
            }
            $baseForm->disableSubmit();
            $baseForm->disableReset();
            $tab->add('基础信息', $baseForm->render());
            if ($info['sku_info']) {
                $skuSpecs = $info['sku_specs'];
                $html = '';
                $specsHeaders = ['规格值', '图片'];
                $skuHeaders = [11 => '供货价(元)', 12 => '市场价(元)', 13 => '最低限价(元)', 14 => '可售库存', 15 => '重量(kg)'];
                foreach ($skuSpecs as $i => $row) {
                    $k = $row['key']['k'];
                    $skuHeaders[$i] = $k;
                    $box = new Box('规格项：' . $k);
                    $values = $row['values'];
                    $specsRows = [];
                    foreach ($values as $value) {
                        $specsRows[] = [
                            $value['v'],
                            $value['url'] ? '<img src="' . $value['url'] . '" width="50" height="50"/>' : '',
                        ];
                    }
                    $table = new Table($specsHeaders, $specsRows);
                    $box->content($table->render());
                    $html .= $box->render();
                }
                ksort($skuHeaders);
                $box = new Box('规格明细：');
                $skus = $info['skus'];
                $skuRows = [];
                foreach ($skus as $sku) {
                    $skuRow = [];
                    foreach ($sku['specs'] as $spec) {
                        $index = array_search($spec['name'], $skuHeaders);
                        $skuRow[$index] = $spec['value'];
                    }
                    $skuRow[11] = $sku['supply_price'];
                    $skuRow[12] = $sku['market_price'];
                    $skuRow[13] = $sku['min_price'];
                    $skuRow[14] = $sku['stock'];
                    $skuRow[15] = $sku['weight'];
                    ksort($skuRow);
                    $skuRows[] = $skuRow;
                }

                $table = new Table($skuHeaders, $skuRows);
                $html .= $box->content($table)->render();
                $tab->add('规格信息', $html);
            }
            $infoContent = '';
            foreach ($info['content'] as $url) {
                $infoContent .= '<p><img src="' . $url . '" style="width: 520px;height: 515px;"/></p>';
            }

            $contentForm = new Form(['content' => $infoContent]);
            $contentForm->html($infoContent);
            $contentForm->disableSubmit();
            $contentForm->disableReset();
            $tab->add('商品详情', $contentForm->render());

            return $content
                ->header('超级补贴 | 商品库详情')
                ->description(' ')
                ->breadcrumb(
                    ['text' => '超级补贴 | 品牌商品库列表', 'url' => url('/admin/SuperSubsidy/brand/goodsList')],
                    ['text' => '商品库详情']
                )
                ->row($tab);
        } else {
            return $content
                ->header('超级补贴 | 商品库详情')
                ->description(' ')
                ->breadcrumb(
                    ['text' => ' 超级补贴 | 品牌商品库列表 ', 'url' => url('/admin/SuperSubsidy/brand/goodsList')],
                    ['text' => '商品库详情']
                )
                ->row();
        }
    }

    public function release(Request $request, $id)
    {
        try {
            $info = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
            if ($info) {
                $spuCode = $info['spu_code'];
                $data = $info;
                $data['no_sku_info'] = json_decode($info['no_sku_info'], true);
                $data['sku_info'] = json_decode($info['sku_info'], true);
                $res = YouZanGoods::brandSpuRelease($spuCode, $data);
                if (!$res) {
                    throw new \Exception('发布商品失败');
                }

            } else {
                throw  new \Exception('不存在的商品信息');
            }
            $success = new MessageBag([
                'title' => '发布商品成功'
            ]);
        } catch (\Exception $e) {
            $success = new MessageBag([
                'title' => $e->getMessage()
            ]);
        }
        return response()->json($success);
    }

    public function exportItem(Request $request, Content $content, $id)
    {
        try {
            $info = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
            if ($info && $info['item_id']) {
                $data = $info;
                $data['no_sku_info'] = $info['no_sku_info'] ? json_decode($info['no_sku_info'], true) : [];
                $data['sku_info'] = $info['sku_info'] ? json_decode($info['sku_info'], true) : [];
                $goodsInfoObj = new YouZanGoodsInfo($data);
                $itemInfo = $goodsInfoObj->getGoodsItemInfo($info['item_id']);
                if (!$itemInfo) {
                    throw new \Exception('获取item商品信息失败');
                }
                $excelData = [];
                foreach ($itemInfo as $row) {
                    $excelData[] = [
                        'spu_code' => $row['spu_code'],
                        'spu_no' => $row['spu_no'],
                        'item_id' => $row['item_id'],
                        'title' => $row['title'],
                        'sku_id' => $row['sku_id'] ?? '',
                        'specifications' => $row['specifications'] ?? '',
                        'supply_price' => $row['supply_price'],
                        'market_price' => $row['market_price'],
                        'min_price' => $row['min_price'],
                    ];
                }
                $sheetData = [
                    ['cell_title' => '商品编码', 'cell_key' => 'A', 'cell_width' => 30, 'value_key' => 'spu_code'],
                    ['cell_title' => '商品条码', 'cell_key' => 'B', 'cell_width' => 30, 'value_key' => 'spu_no'],
                    ['cell_title' => '有赞商城商品id', 'cell_key' => 'C', 'cell_width' => 20, 'value_key' => 'item_id'],
                    ['cell_title' => '商品名称', 'cell_key' => 'D', 'cell_width' => 30, 'value_key' => 'title'],
                    ['cell_title' => 'SKU ID', 'cell_key' => 'E', 'cell_width' => 30, 'value_key' => 'sku_id'],
                    ['cell_title' => '规格', 'cell_key' => 'F', 'cell_width' => 30, 'value_key' => 'specifications'],
                    ['cell_title' => '供货价', 'cell_key' => 'G', 'cell_width' => 20, 'value_key' => 'supply_price'],
                    ['cell_title' => '市场价', 'cell_key' => 'H', 'cell_width' => 20, 'value_key' => 'market_price'],
                    ['cell_title' => '最低限价', 'cell_key' => 'I', 'cell_width' => 20, 'value_key' => 'min_price'],
                ];
                $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
                $sheet = $spreadsheet->getActiveSheet();
                $styleArray = [
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                    ],
                ];
                foreach ($sheetData as $row) {
                    $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
                    $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
                    $sheet->getStyle($row['cell_key'] . '1')->applyFromArray($styleArray);
                }
                $rowNum = 2;
                foreach ($excelData as $info) {
                    foreach ($sheetData as $row) {
                        $key = $row['value_key'];
                        $value = isset($info[$key]) ? $info[$key] : '';
                        $cellKey = $row['cell_key'] . $rowNum;
                        $sheet->setCellValue($cellKey, $value);
                        $sheet->getStyle($cellKey)->applyFromArray($styleArray);
                        $sheet->getCell($cellKey)->setValueExplicit($value, DataType::TYPE_STRING);
                    }
                    $rowNum++;
                }
                $fileName = $info['spu_code'] . '-' . date('YmdHis') . '.xlsx';
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="' . $fileName . '"');
                header('Cache-Control: max-age=0');
                header('Cache-Control: max-age=1');
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
                header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
                header('Pragma: public'); // HTTP/1.0
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save('php://output');
            } else {
                throw new \Exception('不存在的商品信息或不存在有赞商城商品ID');
            }
        } catch (\Exception $e) {
            return $content
                ->header('超级补贴 | 导出item商品')
                ->description(' ')
                ->row('导出item商品信息失败#' . $e->getMessage());
        }
    }


    public function changed(Request $request, $id)
    {
        try {
            $info = YouZanBrandGoodsModel::getByWhere(['id' => $id]);
            if ($info) {
                $res = YouZanBrandGoodsModel::updateData(['status' => YouZanBrandGoodsModel::STATUS_RELEASE], ['id' => $id]);
                if (!$res) {
                    throw new \Exception('更新失败');
                }
            } else {
                throw  new \Exception('不存在的商品信息');
            }
            $success = new MessageBag([
                'title' => '更新成功'
            ]);
        } catch (\Exception $e) {
            $success = new MessageBag([
                'title' => $e->getMessage()
            ]);
        }
        return response()->json($success);
    }


    private function operateGoodsScript()
    {
        return <<<SCRIPT
        $('.release-goods').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/SuperSubsidy/brand/goodsList/'+id+'/release';
            let params = {};
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success(e.title);
                 setTimeout(function () {
                    parent.window.location.reload();
                 }, 2000);
            });
        });
        $('.refresh-goods').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/SuperSubsidy/brand/goodsList/'+id+'/changed';
            let params = {};
            layer.confirm('确定已经手动发布到了网店吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.ajaxSettings.async = true;
                $.post(url, params , function (e) {
                    toastr.success(e.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                });
            });
        });
SCRIPT;
    }

}